<template>
    <view class="upLoad">
        <view class="images">
            <view v-if="loading" class="upLoad_loading loading">
                <u-loading-icon color="#fff"></u-loading-icon>
            </view>
            <img class="images_items" :src="arrData[0]" alt="" @click="imgClick(arrData[0])">
        </view>
        <view class="upLoad_img">
            <u-upload v-if="!look" :width="width" :height="height" :customStyle="{ flex: 'none' }" :previewImage="false"
                :fileList="arrData" @afterRead="afterRead($event)" :maxSize="31457280" :name="name" :multiple="maxCount"
                @oversize="oversize">
                <view class="labels">上传头像</view>
            </u-upload>

        </view>
    </view>
</template>

<script>
import config from '@/config/config.js'
import crypto from 'crypto-js';
import {
    Base64
} from 'js-base64';
import {
    getAliOssSts
} from "@/api/index.js"
export default {
    props: {
        fileList: {
            type: String,
            default: ''
        },
        name: {
            type: String,
            default: '1'
        },
        multiple: {
            type: Boolean,
            default: false
        },
        maxCount: {
            type: Number,
            default: 1
        },
        upLoadType: {
            type: String,
            default: 'img'
        },
        look: {
            type: Boolean,
            default: false
        },
        width: {
            type: String,
            default: '90px'
        },
        height: {
            type: String,
            default: '90px'
        },
        previewButton: {
            type: Boolean,
            default: true
        },
        place: {
            type: String,
        }
    },
    data() {
        return {
            loading: false
        };
    },
    computed: {
        // 计算属性，将数据处理成带有http路径的数组，好在页面展示
        arrData() {
            // 传入的是字符串，判断字符串是不是空，空字符转转换成空数组，字符串有内容，直接转成数组，拼接https的路径
            if (this.fileList) {
                let arr = this.fileList.split(',')
                const urlArr = []
                arr.forEach(item => {
                    if (!item.includes(config.pic_prefix)) {
                        urlArr.push(`${config.pic_prefix}${item}?x-oss-process=image/resize,w_300`)
                    } else {
                        urlArr.push(`${item}?x-oss-process=image/resize,w_300`)
                    }
                })
                return urlArr
            } else {
                return []
            }
        }
    },
    methods: {
        async GetAliOssSts() {
            const res = await getAliOssSts()
            return res.data
        },
        async afterRead(value) {
            this.loading = true
            const {
                accessKeyId,
                accessKeySecret,
                securityToken
            } = await this.GetAliOssSts()
            const arr = this.fileList ? this.fileList.split(',') : []
            const loadingArr = []
            value.file.map(async (item, index) => {
                loadingArr.push(false)
                this.uploadFilePromise(item.url, {
                    accessKeyId,
                    accessKeySecret,
                    securityToken
                }, index, (url, ind) => {
                    loadingArr[ind] = true
                    // arr.push(url)
                    arr[0] = url
                    const str = arr.join(',')
                    console.log(str)
                    this.$emit('onChange', str)
                    if (loadingArr.every((ite) => {
                        return ite
                    })) {
                        this.loading = false
                    }
                })
            })
        },
        // 新增商品上传
        uploadFilePromise(url, {
            accessKeyId,
            accessKeySecret,
            securityToken
        }, index, fn) {
            let _that = this
            let fileName = `${new Date().getTime()}.${url.split('.').pop()}`
            const date = new Date();
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const dateR = date.getDate();
            date.setHours(date.getHours() + 1)
            const policy = Base64.encode(JSON.stringify({
                expiration: date.toISOString(), // 设置policy过期时间。
                conditions: [
                    // 限制上传大小。
                    ["content-length-range", 0, 30 * 1024 * 1024],
                ],
            }))
            uni.uploadFile({
                url: config.pic_prefix,
                filePath: url,
                name: 'file', // 必须填file。
                formData: {
                    signature: crypto.enc.Base64.stringify(crypto.HmacSHA1(policy, accessKeySecret)),
                    OSSAccessKeyId: accessKeyId,
                    policy,
                    key: `uploads/${year}/${month}/${dateR}/${fileName}`,
                    'x-oss-security-token': securityToken // 使用STS签名时必传。
                },
                success: (data) => {
                    // 处理路径，返回的路径是http的，将http干掉，跟之前的url拼接一下，已逗号的形式拼接，然后存入fileList中
                    fn(`uploads/${year}/${month}/${dateR}/${fileName}`, index)
                },
            });
        },
        // 判断当前是pdf还是img
        isPdf(url) {
            return url.includes(".pdf")
        },
        // pdf上传，打开微信聊天记录，从中选择pdf文件进行上传
        selectFile() {
            let _that = this
            wx.chooseMessageFile({
                count: _that.maxCount - (_that.fileList ? _that.fileList.split(',').length :
                    0), //最多可以选择的文件个数，可以 0～100
                type: 'file', //所选的文件的类型，具体看官方文档
                async success(res) {
                    _that.loading = true
                    const {
                        accessKeyId,
                        accessKeySecret,
                        securityToken
                    } = await _that.GetAliOssSts()
                    let isName = res.tempFiles.every(item => {
                        return item.path.indexOf(".pdf") !== -1
                    })
                    if (!isName) {
                        uni.showToast({
                            title: "暂时仅支持pdf格式的文件！",
                            icon: 'none'
                        });
                        return
                    }
                    let isSize = res.tempFiles.every(item => {
                        return item.size <= 31457280
                    })
                    if (!isSize) {
                        uni.showToast({
                            title: "文件过大无法上传，请拆分后上传~",
                            icon: 'none'
                        });
                        return
                    }
                    const arr = _that.fileList ? _that.fileList.split(',') : []
                    const loadingArr = []
                    // tempFilePath可以作为img标签的src属性显示图片
                    res.tempFiles.forEach((item, index) => {
                        loadingArr.push(false)
                        // 这一步判断可以省略，如果需求没有格式要求的话
                        let fileName = `${new Date().getTime()}.${item.path.split('.').pop()}`
                        const date = new Date();
                        const year = date.getFullYear();
                        const month = date.getMonth() + 1;
                        const dateR = date.getDate();
                        date.setHours(date.getHours() + 1)
                        const policy = Base64.encode(JSON.stringify({
                            expiration: date.toISOString(), // 设置policy过期时间。
                            conditions: [
                                // 限制上传大小。
                                ["content-length-range", 0, 30 * 1024 * 1024],
                            ],
                        }))
                        wx.uploadFile({
                            url: config.pic_prefix,
                            filePath: item.path,
                            name: 'file', // 必须填file。
                            formData: {
                                signature: crypto.enc.Base64.stringify(crypto.HmacSHA1(
                                    policy, accessKeySecret)),
                                OSSAccessKeyId: accessKeyId,
                                policy,
                                key: `uploads/${year}/${month}/${dateR}/${fileName}`,
                                'x-oss-security-token': securityToken // 使用STS签名时必传。
                            },
                            success(res) {
                                if (res.statusCode === 204) {
                                    loadingArr[index] = true
                                    arr.push(
                                        `uploads/${year}/${month}/${dateR}/${fileName}`
                                    )
                                    const str = arr.join(',')
                                    _that.$emit('onChange', str)
                                    if (loadingArr.every((ite) => {
                                        return ite
                                    })) {
                                        _that.loading = false
                                    }
                                } else {
                                    uni.showToast({
                                        title: '文件上传失败，请检查网络',
                                        icon: 'none'
                                    })
                                }
                            }
                        })
                    })
                }
            })
        },
        // 删除上传的pdf或img
        upLoadDelete(url) {
            const arr = JSON.parse(JSON.stringify(this.arrData))
            let index = arr.indexOf(url); // 查找元素的索引
            if (index > -1) {
                arr.splice(index, 1); // 从索引处删除一个元素
                if (arr.length) {
                    // 根据url查找之后删除，但是arr数组中存入的url带有https路径，将https路径干掉，转成字符串，存入fileList中
                    const strArr = []
                    arr.forEach(item => {
                        strArr.push(item.split(config.pic_prefix)[1].split('?')[0])
                    })
                    const str = strArr.join(',')
                    this.$emit('onChange', str)
                } else {
                    this.$emit('onChange', '')
                }
            }
        },
        // 图片预览
        imgClick(url) {
            uni.previewImage({
                urls: [url.split('?')[0]], //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
                current: '', // 当前显示图片的http链接，默认是第一个
            })
        },
        // 下载pdf、预览
        downloadClick(item) {
            let url = item.split('?')[0]
            uni.downloadFile({
                url: url,
                success: res => {
                    if (res.statusCode === 200) {
                        // 预览pdf文件
                        uni.openDocument({
                            filePath: res.tempFilePath,
                            showMenu: true,
                            success: function (file) {
                                console.log("文件打开成功", file)
                            }
                        })
                    }
                }
            })
        },
        // 文件上传超出大小，提示
        oversize(file) {
            wx.showToast({
                title: '文件过大无法上传，请拆分后上传~',
                icon: 'none',
                duration: 2000 // 提示消息显示时长，单位为毫秒
            });
        },
    }
};
</script>

<style lang="less">
.images {
    width: 150rpx;
    height: 150rpx;
    border: 1px solid #e3e3e3;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;

    .loading {
        width: 150rpx;
        height: 150rpx;
        border-radius: 50%;
    }

    .images_items {
        border-radius: 50%;
        height: 100%;
        width: 100%;
        background-color: #fff;
    }
}

.labels {
    width: 150rpx;
    text-align: center;
    margin-top: 20rpx;
}

.upLoad {
    // display: flex;
    align-items: flex-start;
    flex-wrap: wrap;

    .upLoad_list {
        margin-right: 8px;
        margin-bottom: 8px;
        border-radius: 2px;
        overflow: hidden;
        position: relative;

        .upLoad_list_pdf {
            background-color: #f4f5f7;
            border-radius: 2px;
            box-sizing: border-box;
            display: flex;
            flex-flow: column;
            align-items: center;
            justify-content: center;

            .upLoad_list_pdf_title {
                margin-top: 8px;
                color: #0094FF;
            }
        }

        .upLoad_list_delect {
            position: absolute;
            top: 0;
            right: 0;
            background-color: #373737;
            height: 14px;
            width: 14px;
            display: flex;
            flex-direction: row;
            border-bottom-left-radius: 100px;
            align-items: center;
            justify-content: center;
            z-index: 3;
        }
    }

    .upLoad_img {
        position: relative;
        font-size: 15px;
        color: #303133;

        .loading {
            width: calc(100% - 8px);
            height: calc(100% - 8px);
        }

        .place {
            font-size: 22rpx;
            color: rgb(179, 173, 173);
        }
    }

    .upLoad_pdf {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background-color: #f4f5f7;
        border-radius: 2px;
        margin: 0 8px 8px 0;
        box-sizing: border-box;
        position: relative;

        .upLoad_pdf_icon {
            width: 13px;
            height: 13px;
        }

        .loading {
            width: 100%;
            height: 100%;
        }
    }

    .upLoad_loading {
        position: absolute;
        top: 0;
        left: 0;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
</style>